package com.data.structure.node;

/**
 * 描述:
 * 自定义扩容数组
 *
 * @author luzhongfu
 * @create 2018-12-23 7:11 PM
 */
public class MyVector<T> {

    private Object[] data;

    private int size;

    private int capacity;

    public MyVector(){
        this.data = new Object[10];
        this.capacity = 10;
        this.size = 0;
    }

    public MyVector(int capacity){
        this.data = new Object[capacity];
        this.capacity = capacity;
        this.size = 0;
    }

    public int size(){
        return this.size;
    }

    private void resize(int newCapacity){
        Object[] newData = new Object[newCapacity];
        for ( int i = 0 ; i < size ; i++ ){
            newData[i] = data[i];
        }
        this.capacity = newCapacity;
        this.data = newData;
    }

    public void pushBack(T o){
        if( size == capacity )
            resize(2*capacity);
        data[size ++] = o;
    }

    public T popBack(){
        T result = (T) data[size - 1];
        if( size == capacity/4 )
            resize(capacity/2);
        size--;
        return result;
    }

    public T get(int k){
        if( k >= size ){
            return null;
        }
        return (T) data[k-1];
    }
}
